#ifndef __M_CONNECTION_H__
#define __M_CONNECTION_H__

#include "muduo/proto/dispatcher.h"
#include "muduo/proto/codec.h"
#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpClient.h"
#include "muduo/base/CountDownLatch.h"
#include "muduo/net/EventLoopThread.h"

#include "mq_worker.hpp"
#include "mq_channel.hpp"

namespace zymq
{
    class Connection
    {
    public:
        using ptr = std::shared_ptr<Connection>;

        Connection(const std::string &sip, int sport, const AsyncWorker::ptr &worker) : 
                    _latch(1),
                    _client(worker->loopthread.startLoop(), muduo::net::InetAddress(sip, sport), "Client"),
                    _dispatcher(std::bind(&Connection::onUnknownMessage, this, std::placeholders::_1,std::placeholders::_2, std::placeholders::_3)),
                    _codec(std::make_shared<ProtobufCodec>(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher,std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))),
                    _worker(worker),
                    _channel_manager(std::make_shared<ChannelManager>())
        {
            // 注册业务请求处理函数
            _dispatcher.registerMessageCallback<zymq::basicCommonResponse>(std::bind(&Connection::basicResponse, this,
                        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
            _dispatcher.registerMessageCallback<zymq::basicConsumeResponse>(std::bind(&Connection::consumeResponse, this,
                        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));


            _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, _codec.get(),
                        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

            _client.setConnectionCallback(std::bind(&Connection::onConnection, this, std::placeholders::_1));

            _client.connect();
            _latch.wait(); // 阻塞等待，知道连接建立成功
        }
        Channel::ptr openChannel()
        {
            auto channel = _channel_manager->create(_conn, _codec);
            bool ret = channel->openChannel();

            return ret == false ? nullptr : channel;
        }
        void closeChannel(const Channel::ptr &channel)
        {
            channel->closeChannel();
            _channel_manager->remove(channel->cid());
        }

    private:
        void basicResponse(const muduo::net::TcpConnectionPtr &conn, const basicCommonResponsePtr &message, muduo::Timestamp)
        {
            Channel::ptr channel = _channel_manager->get(message->cid());
            if(channel.get() == nullptr)
            {
                DLOG("未找到信道信息");
                return;
            }
            channel->putBasicResponse(message);
        }
        void consumeResponse(const muduo::net::TcpConnectionPtr &conn, const basicConsumeResponsePtr &message, muduo::Timestamp)
        {
            Channel::ptr channel = _channel_manager->get(message->cid());
            if(channel.get() == nullptr)
            {
                DLOG("未找到信道信息");
                return;
            }
            _worker->pool.push([channel, message](){
                channel->consume(message);
            });
        }
        void onUnknownMessage(const muduo::net::TcpConnectionPtr &conn, const MessagePtr &message, muduo::Timestamp)
        {
            LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
            conn->shutdown();
        }
        void onConnection(const muduo::net::TcpConnectionPtr &conn)
        {
            if (conn->connected())
            {
                _latch.countDown();
                _conn = conn;
            }
            else
            {
                // 连接关闭时的操作
                _conn.reset();
            }
        }

    private:
        muduo::CountDownLatch _latch;
        muduo::net::TcpConnectionPtr _conn;
        muduo::net::TcpClient _client;

        ProtobufDispatcher _dispatcher;
        ProtobufCodecPtr _codec;

        AsyncWorker::ptr _worker;
        ChannelManager::ptr _channel_manager;
    };
}

#endif